package Util

import (
	"deepgox-go-admin/Infrastructures/Redis"
	"fmt"
	"github.com/mojocn/base64Captcha"
	"image/color"
	"time"
)

const CAPTCHA = "captcha:"

type RedisStore struct {
}

// Set 实现设置 captcha 的方法
func (r RedisStore) Set(id string, value string) error {
	key := CAPTCHA + id
	err := Redis.Rdb.Set(key, value, time.Minute*2).Err()
	return err
}

// Get 实现获取 captcha 的方法
func (r RedisStore) Get(id string, clear bool) string {
	key := CAPTCHA + id
	//获取 captcha
	val, err := Redis.Rdb.Get(key).Result()
	if err != nil {
		fmt.Println(err)
		return ""
	}
	//如果clear == true, 则删除
	if clear {
		err := Redis.Rdb.Del(key).Err()
		if err != nil {
			fmt.Println(err)
			return ""
		}
	}
	return val
}

// Verify 实现验证 captcha 的方法
func (r RedisStore) Verify(id, answer string, clear bool) bool {
	v := RedisStore{}.Get(id, clear)
	return v == answer
}

var store base64Captcha.Store = RedisStore{}

// MakeCaptcha 获取验证码
func MakeCaptcha() (string, string, error) {
	//定义一个driver
	var driver base64Captcha.Driver
	//创建一个字符串类型的验证码驱动DriverString, DriverChinese :中文驱动
	driverString := base64Captcha.DriverString{
		Height:          32,                                  //高度
		Width:           100,                                 //宽度
		NoiseCount:      15,                                  //干扰数
		ShowLineOptions: 2 | 2,                               //展示个数
		Length:          4,                                   //长度
		Source:          "123456789wertyuiplkjhgfdsazxcvbnm", //验证码随机字符串来源
		BgColor: &color.RGBA{ // 背景颜色
			R: 254,
			G: 254,
			B: 254,
			A: 254,
		},
		Fonts: []string{"wqy-microhei.ttc"}, // 字体
	}
	driver = driverString.ConvertFonts()
	//生成验证码
	c := base64Captcha.NewCaptcha(driver, store)
	id, b64s, _, err := c.Generate()
	return id, b64s, err
}

// VerifyCaptcha 校验验证码
func VerifyCaptcha(id string, VerifyValue string) bool {
	// 参数说明: id 验证码id, verifyValue 验证码的值, true: 验证成功后是否删除原来的验证码
	if store.Verify(id, VerifyValue, true) {
		return true
	} else {
		return false
	}
}
